package com.example.nettyRpc.server;
import java.net.InetAddress;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

import com.example.nettyRpc.constant.Constants;
import com.example.nettyRpc.factory.ZookeeperFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MyServer {
	public static void main(String[] args) throws Exception {
		//接受客户端连接
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		//处理客户端连接   从bossGroup接受客户端连接
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
		ServerBootstrap sb = new ServerBootstrap();
		sb.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.option(ChannelOption.SO_BACKLOG, 128)
			.option(ChannelOption.SO_KEEPALIVE, false)
			.childHandler(new MyServerInitializer());
		ChannelFuture cf = sb.bind(8899).sync();


// -----------------把netty服务器注册到zookeeper上-------------------------
		// 1、连接zookeeper
		CuratorFramework client = ZookeeperFactory.create();

		// 2、创建 netty服务器 节点
		InetAddress netAddress = InetAddress.getLocalHost();
		client.create()
			.withMode(CreateMode.EPHEMERAL)//临时节点
			.forPath(Constants.SERVER_PATH+netAddress.getHostAddress());//节点名称/路径
// -------------------------------------------------------------------



		cf.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}

	}
}
